//
//  SystemInfoVC.m
//  Brand
//
//  Created by Faker on 5/16/14.
//  Copyright (c) 2014 Faker. All rights reserved.
//

#import "SystemInfoVC.h"
#import "SystemInfoObj.h"
#import "NewsDetailVC.h"
#import "VideoDetailVC.h"
#import "VideoObj.h"
#import "VipVC.h"
#import "MyLevelViewController.h"
#import "Header.h"

@interface SystemInfoVC ()
@property (weak, nonatomic) IBOutlet UIView *navTopContentView;
@property (weak, nonatomic) IBOutlet UITableView *myTableView;

@property (strong, nonatomic) NSMutableArray* dataArray;

@end

@implementation SystemInfoVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self drawNavTopContentView:self.navTopContentView];
    [self setUp];
}

-(void)viewWillAppear:(BOOL)animated
{
   
    [self.myTableView reloadData];
}

-(void)setUp
{
    self.dataArray = [[NSMutableArray alloc]init];
    [self prepareGetData];
}

#pragma mark - 网络请求
-(void)prepareGetData
{
    [kApp displayWaitViewWithAllMaskView:NO];
    
    NSString* url = [NSString stringWithFormat:@"%@getSysMsg&pf=2&uid=%@",API_BASE,[[UserObj sharedInstance] uid]];
    
    [[AFGetData sharedInstance] startGet:url andResultIsJSON:YES andRequestCompletion:^(id responseObj, BOOL isSuccess) {
        if(isSuccess)
        {
            [self getDataSuccess:responseObj];
        }
        else{
            [self getDataError];
        }
    }];
}

-(void)getDataSuccess:(id)responseObj
{
    [kApp hideWaitView];
    
    NSMutableArray* netArray = [[NSMutableArray alloc]init];
    if(IsArray(responseObj))
    {
       NSArray* tempArray = (NSArray*)responseObj;
      for (NSDictionary* dic in tempArray) {
            SystemInfoObj* obj  = [[SystemInfoObj alloc]init];
            obj.mId =     [dic objectForKey:@"id"];
            obj.title =   [dic objectForKey:@"title"];
            obj.content = [dic objectForKey:@"cont"];
            obj.pic = [dic objectForKey:@"pic"];
            obj.url = [dic objectForKey:@"url"];
            obj.videoId = [dic objectForKey:@"vid"];
            obj.msgType = [dic objectForKey:@"msg_type"];
            obj.updateTime = [dic objectForKey:@"update_time"];
            [netArray addObject:obj];
        }
         //[UserDataBasic setObject:[[netArray lastObject] mId] forKey:LocalSystemMaxId];
    }
   
    [self handleDataWithArray:netArray];
}

-(void)handleDataWithArray:(NSArray*)array
{
    self.dataArray = [UserDataBasic readObjectArrayForKey:LocalSystemData];
    
    if(IsNull(self.dataArray)||[self.dataArray count] == 0)
    {
        self.dataArray = [NSMutableArray array];
    }
    if(!IsNull(array))
    {
       
        for (SystemInfoObj* obj in array) {
            [self.dataArray insertObject:obj atIndex:0];
        }
    }
    [UserDataBasic saveThisObjectArray:self.dataArray forArrayKey:LocalSystemData];
    
    if(![self.dataArray count])
    {
        [PopTips tips:kApp.rootNav.view Msg:NotifyNoMessage];
        [self performSelector:@selector(goBack:) withObject:self afterDelay:0.7];
    }
    else{
    
        [self.myTableView reloadData];
    }
}

-(void)getDataError
{
    [kApp hideWaitView];
    [PopTips tips:self.view Msg:NotifyNoNet];
    [self performSelector:@selector(goBack:) withObject:self afterDelay:0.7];
    //[self handleDataWithArray:nil];
}


#pragma mark - 点一条，删一条
-(void)removeObjFromLocalArray:(SystemInfoObj*)infoObj
{
    [self.dataArray removeObject:infoObj];
    [UserDataBasic saveThisObjectArray:self.dataArray forArrayKey:LocalSystemData];
}


#pragma mark - UITableView methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataArray count];
    //return 10;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* identifier = @"identifier";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if(cell == nil)
    {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"SystemInfoCell" owner:self options:nil]lastObject];
    }
    
    SystemInfoObj* obj = [self.dataArray objectAtIndex:indexPath.row];
    
    UIImageView* imageView = (UIImageView*)[cell viewWithTag:302];
    UILabel* titleLabel = (UILabel*)[cell viewWithTag:200];
    UILabel* infoLabel = (UILabel*)[cell viewWithTag:202];
    UILabel* timeLabel = (UILabel*)[cell viewWithTag:203];
    
    imageView.layer.cornerRadius = imageView.width/2;
    imageView.clipsToBounds = YES;
    [[AFGetData sharedInstance] initSDWebImage:obj.pic andTrueImageView:imageView andPlaceholderImage:[UIImage imageNamed:@"person_fake.png"]];
    titleLabel.text = obj.title;
    //infoLabel.text = obj.content;
    [Common handleTheLabelHeight:infoLabel withText:obj.content withMaxHeight:30];
    timeLabel.text = obj.updateTime;
    
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 62;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //NSLog(@"index.row = %d",indexPath.row);
    SystemInfoObj* obj = [self.dataArray objectAtIndex:indexPath.row];
    [self removeObjFromLocalArray:obj];
    int msgType = [obj.msgType intValue];
    NSLog(@"msgType = %d",msgType);
    switch (msgType) {
        case 1: //资讯
            [self goToNewsInfoWithObj:obj];
            break;
        case 2: //appStore
            [self goToAppStoreWithAppId:obj.url];
            [Common getWYByPostWithType:@"6" andItemId:@"0"];
            break;
        case 3: //个人中心首页
            [self goToPersonCenter];
            break;
        case 4: //我的文耀
            [self goToWenYao];
            break;
        case 5: //系统升级
            [self goToAppStoreWithAppId:obj.url];
            break;
        case 6: //升级vip
            [self goToVip];
            break;
        case 7: //vip页面
            [self goToVip];
            break;
        case 8: //播放详情
            [self goToVideoDetailWithObj:obj];
            break;
        default:
            break;
    }
    [Common getWYByPostWithType:@"2" andItemId:@"0"];
}

#pragma mark - 资讯
-(void)goToNewsInfoWithObj:(SystemInfoObj*)infoObj
{
    NewsDetailVC* newsVC = [[NewsDetailVC alloc]initWithNibName:@"NewsDetailVC" bundle:nil];
    newsVC.title = infoObj.title;
    NSDictionary* dic = [NSDictionary dictionaryWithObjectsAndKeys:infoObj.url,@"url", nil];
    NSArray* array = [NSArray arrayWithObjects:dic, nil];
    newsVC.dataArray = array;
    [self.navigationController pushViewController:newsVC animated:YES];
}

#pragma mark - appStore
-(void)goToAppStoreWithAppId:(NSString*)appId
{
    //初始化控制器
    SKStoreProductViewController *storeProductViewContorller = [[SKStoreProductViewController alloc] init];
    //设置代理请求为当前控制器本身
    storeProductViewContorller.delegate = self;
    //加载一个新的视图展示
    [storeProductViewContorller loadProductWithParameters:
     //appId唯一的
     @{SKStoreProductParameterITunesItemIdentifier : appId} completionBlock:^(BOOL result, NSError *error) {
         //block回调
         if(error){
           
         }else{
             //模态弹出appstore
             [self presentViewController:storeProductViewContorller animated:YES completion:^{
                
             }
              ];
         }
     }];
    
}

//取消按钮监听
- (void)productViewControllerDidFinish:(SKStoreProductViewController *)viewController{
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}


#pragma mark - 个人中心
-(void)goToPersonCenter
{
    kApp.meHomeVC = [[MeHomeViewController alloc] initWithNibName:@"MeHomeViewController" bundle:nil];
    [self.navigationController pushViewController:kApp.meHomeVC animated:YES];

}

#pragma mark - 我的文耀
-(void)goToWenYao
{
   
     MyLevelViewController *myLevelVC = [MyLevelViewController new];
    [self.navigationController pushViewController:myLevelVC animated:YES];
    
}

#pragma mark - 播放详情页
-(void)goToVideoDetailWithObj:(SystemInfoObj*)obj
{
    VideoDetailVC* detailVC = [[VideoDetailVC alloc]initWithNibName:@"VideoDetailVC" bundle:nil];
    VideoObj* videoObj = [[VideoObj alloc]init];
    
    videoObj.episodeId = obj.videoId;
    NSLog(@"videoId = %@",obj.videoId);
    detailVC.videoObj = videoObj;
    [self.navigationController pushViewController:detailVC animated:YES];
}


#pragma mark - 升级vip
-(void)goToVip
{
    VipVC* vipVC = [[VipVC alloc]initWithNibName:@"VipVC" bundle:nil];
    [self.navigationController pushViewController:vipVC animated:YES];
}

#pragma mark - xib点击事件
- (IBAction)goBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)deleteAll:(id)sender {
    [self.dataArray removeAllObjects];
    [UserDataBasic saveThisObjectArray:self.dataArray forArrayKey:LocalSystemData];
    [self.myTableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
